<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>动手实验</title>
    <link rel="stylesheet" href="../../css/L1/labor_01.css" />
    <script
      src="../../plugins/jquery-3.6.0.min.js"
      type="text/javascript"
    ></script>
    <script src="../../plugins/zrender.min.js"></script>
    <script src="../../plugins/pixi.js"></script>
    <script src="../../plugins/bump.js"></script>
    <script src="../../plugins/tink.js"></script>
  </head>
  <body>
    <div class="main" id="main">
      <!-- 这里是返回条的div -->
      <div id="backbar">
        <div id="backbutton">&lt</div>
        <!-- <div id="backtitle">动手实验</div> -->
        <div id="playicon"></div>
      </div>
      <!-- 在这里设置一个实验完成的遮罩 -->
      <div class="shadowPanel">
        <div class="controlbox">
          <div class="replay">
            <img src="../../images/再玩一遍.png" alt="再看一遍" />
            <p>再玩一遍</p>
          </div>
          <div class="nextItem">
            <img src="../../images/下一环节.png" alt="下一环节" />
            <p>下一环节</p>
          </div>
        </div>
      </div>
    </div>
  </body>
  <script type="module">
    import { modifyCourseStatus } from '../../js/modify_course_status.js'

    window.onload = function () {
      let DESIGN_WIDTH = 1334
      let DESIGN_HEIGHT = 750
      // 初始化及基准rem的值
      document.documentElement.style.fontSize =
        (window.innerHeight * 12) / DESIGN_WIDTH + 'px'

      // 当前实验是否播放声音
      // let audioplay = true
      let audio
      let playing = {
        'background-image': 'url(../../images/播放着.png)',
        'background-size': '80%',
        'background-repeat': 'no-repeat',
        'background-position': 'center',
      }

      let toPlay = {
        'background-image': 'url(../../images/点击播放.png)',
        'background-size': '80%',
        'background-repeat': 'no-repeat',
        'background-position': 'center',
      }

      let currentAudioUrl = ''
      // pixijs
      let app, loader
      let huangguan_1, huangguan_2, huangguan_3, shaobei_1, shaobei_2, shaobei_3
      let message
      let ans_right, ans_error
      let cupArray = [],
        crownArray = []

      // style  control
      let create_crown_conut = 0,
        create_cup_conunt = 0
      // 归为原点记录
      let initX, initY
      // bump.js
      let b = new Bump(PIXI)
      // window
      let windowWidth = window.innerWidth
      let windowHeight = window.innerHeight
      // tink.js
      let tink
      let state = play

      // if (windowHeight / windowWidth < DESIGN_WIDTH / DESIGN_HEIGHT) {
      //   $("html").css({
      //     height: (windowWidth * DESIGN_WIDTH) / DESIGN_HEIGHT,
      //   });
      // }

      function initApp() {
        app = new PIXI.Application({
          resolution: 3,
          width: windowWidth,
          height: windowHeight,
          autoDensity: true,
        })
        app.renderer.backgroundColor = 0xfef6ef
        document.getElementById('main').appendChild(app.view)
        loader = new PIXI.Loader()
        loader.add([
          '../../images/rowimages_01/皇冠1.png',
          '../../images/rowimages_01/皇冠2.png',
          '../../images/rowimages_01/皇冠3.png',
          '../../images/有水的水桶1.png',
          '../../images/有水的水桶2.png',
          '../../images/有水的水桶3.png',
          '../../images/rowimages_01/漫水空.png',
          '../../images/rowimages_01/漫水空_03.png',
          '../../images/rowimages_01/漫水少.png',
          '../../images/rowimages_01/漫水中.png',
          '../../images/rowimages_01/漫水多.png',
          '../../images/未放入的水桶.png',
          '../../images/rowimages_01/位置框.png',
          '../../images/rowimages_01/正确、.png',
          '../../images/rowimages_01/错误.png',
          // "../../images/16pic_6962525_cc1c79f6.svg",
        ])
        tink = new Tink(PIXI, app.view)
      }
      // 创建背景精灵
      function setBackground() {
        let bg = loader.load(setupBg)
        function setupBg() {
          let bgimage = new PIXI.Sprite(
            loader.resources['../../images/rowimages_01/位置框.png'].texture
          )
          bgimage.width = (windowWidth * 160) / DESIGN_HEIGHT
          bgimage.height = windowHeight
          bgimage.x = (windowWidth * 460) / DESIGN_HEIGHT
          app.stage.addChild(bgimage)
        }
      }
      // 创建烧杯精灵
      function createCupScript() {
        let shaobei = new PIXI.Sprite(
          loader.resources['../../images/rowimages_01/漫水空_03.png'].texture
        )
        shaobei.buttonMode = true
        // shaobei.interactive = true
        shaobei.interactive = false
        shaobei.ishave = false
        shaobei.width = (windowHeight * 203) / DESIGN_WIDTH
        shaobei.height = (windowWidth * 388) / DESIGN_HEIGHT
        let baseLineLeft = parseInt(windowHeight / 3) * create_cup_conunt
        // let offsetLeft = (parseInt(windowHeight / 3) - shaobei.width) / 2;
        let offsetLeft = (windowHeight * 20) / DESIGN_HEIGHT
        shaobei.y = baseLineLeft + offsetLeft
        // shaobei.x = (app.view.height * 430) / DESIGN_HEIGHT;
        shaobei.x = (windowWidth * 53) / DESIGN_WIDTH
        shaobei.on('pointerup', onCupButtonUp)
        tink.makeInteractive(shaobei)
        // shaobei.zIndex = 4
        shaobei.id = create_cup_conunt
        create_cup_conunt++
        return shaobei
      }

      // 创建第一个烧杯精灵
      function createCupSpriteOne() {
        let cup = loader.load(cupSetup)
        function cupSetup() {
          shaobei_1 = createCupScript()
          app.stage.addChild(shaobei_1)
          cupArray.push(shaobei_1)
        }
      }

      // 创建第二个烧杯精灵
      function createCupSpriteTwo() {
        let cup = loader.load(cupSetup)
        function cupSetup() {
          shaobei_2 = createCupScript()
          app.stage.addChild(shaobei_2)
          cupArray.push(shaobei_2)
        }
      }

      // 创建地三个烧杯精灵
      function createCupSpriteThree() {
        let cup = loader.load(cupSetup)
        function cupSetup() {
          shaobei_3 = createCupScript()
          app.stage.addChild(shaobei_3)
          cupArray.push(shaobei_3)
        }
      }
      // 创建皇冠精灵
      function createCrownSprite(offsetx, offsety) {
        let resourcesstr =
          '../../images/rowimages_01/皇冠' + (create_crown_conut + 1) + '.png'
        let huangguan = new PIXI.Sprite(loader.resources[resourcesstr].texture)
        huangguan.buttonMode = true
        huangguan.interactive = true
        huangguan.roundPixels = true
        huangguan.isMove = false
        huangguan.width = (windowHeight * 99) / DESIGN_WIDTH
        huangguan.height = (windowWidth * 150) / DESIGN_HEIGHT
        huangguan.x = (windowWidth * offsetx) / DESIGN_HEIGHT
        huangguan.y = (windowHeight * offsety) / DESIGN_WIDTH
        huangguan.on('pointerup', onCrownButtonUp)
        huangguan.on('pointerdown', onCrownButtonDown)
        tink.makeDraggable(huangguan)
        tink.makeInteractive(huangguan)
        create_crown_conut++
        return huangguan
      }

      // 创建第一个皇冠精灵
      function crateCrownScriptOne() {
        let crown = loader.load(crownSetup)
        function crownSetup() {
          huangguan_1 = createCrownSprite(490, 356)
          huangguan_1.name = 'huangguan_1'
          app.stage.addChild(huangguan_1)
        }
      }

      // 创建第二个皇冠精灵
      function crateCrownScriptTwo() {
        let crown = loader.load(crownSetup)
        function crownSetup() {
          huangguan_2 = createCrownSprite(490, 610)
          huangguan_2.name = 'huangguan_2'
          app.stage.addChild(huangguan_2)
        }
      }

      // 创建第三个皇冠精灵
      function crateCrownScriptThree() {
        let crown = loader.load(crownSetup)
        function crownSetup() {
          huangguan_3 = createCrownSprite(490, 856)
          huangguan_3.name = 'huangguan_3'
          app.stage.addChild(huangguan_3)
        }
      }

      // 创建结果精灵
      function createResultSprite() {
        loader.load(setupRes)
        function setupRes() {
          ans_right = new PIXI.Sprite(
            loader.resources['../../images/rowimages_01/正确、.png'].texture
          )
          ans_error = new PIXI.Sprite(
            loader.resources['../../images/rowimages_01/错误.png'].texture
          )
          ans_right.width = (windowWidth * 60) / DESIGN_HEIGHT
          ans_right.height = ans_right.width
          ans_error.width = (windowWidth * 60) / DESIGN_HEIGHT
          ans_error.height = ans_error.width
          ans_right.visible = false
          ans_error.visible = false
          app.stage.addChild(ans_right, ans_error)
        }
      }

      // 鼠标在皇冠上抬起的时候的事件处理函数
      function onCrownButtonUp(e) {
        let that = this
        if (b.hit(this, shaobei_1)) {
          if (!shaobei_1.ishave) {
            // 放入烧杯
            intoCup(that, shaobei_1)
          } else {
            // 皇冠返回原处
            crownBack(that)
          }
        } else if (b.hit(this, shaobei_2)) {
          if (!shaobei_2.ishave) {
            // 放入烧杯
            intoCup(that, shaobei_2)
          } else {
            // 皇冠返回原处
            crownBack(that)
          }
        } else if (b.hit(this, shaobei_3)) {
          if (!shaobei_3.ishave) {
            // 放入烧杯
            intoCup(that, shaobei_3)
          } else {
            // 皇冠返回原处
            crownBack(that)
          }
        } else {
          // 皇冠返回
          crownBack(that)
        }
        this.isMove = false
      }

      // 当鼠标在皇冠上点几下去时的处理函数
      function onCrownButtonDown() {
        let _this = this
        initX = _this.x
        initY = _this.y
        _this.isMove = true
      }

      // 当鼠标在烧杯上点击结束之后的处理事件
      async function onCupButtonUp() {
        console.log('当前的点击的木桶', this)

        alphaAdd(this, cupArray)
        // 当选择的结果是正确的时候
        if (this.isLargest && this.ishave) {
          ans_right.x = this.x + (windowWidth * 15) / DESIGN_HEIGHT
          ans_right.y = this.y + (windowHeight * 185) / DESIGN_WIDTH
          ans_right.visible = true
          ans_error.visible = false
          let shadowPanel = $('.shadowPanel')
          // 调用选择正确时候的音效
          playAudio('../../audio/L1/正确音效.mp3').then((resolve) => {
            console.log(resolve)
            resolve.addEventListener('ended', function (e) {
              playAudio('../../audio/L1/这个皇冠体积最大.mp3').then(
                (resolve) => {
                  resolve.addEventListener('ended', function (e) {
                    playicon.css(toPlay)
                    shadowPanel.show()
                    //TODO: 当实验完成且语音播放结束时，我们来改变课程的学习状态
                    modifyCourseStatus(
                      1,
                      {
                        story_finish: true,
                        principle_finish: true,
                        labor_finish: true,
                        report_finish: false,
                      },
                      {
                        second_lock: false,
                        third_lock: false,
                        fourth_lock: false,
                      }
                    )
                  })
                }
              )
            })
          })
        } else if (this.ishave && !this.isLargest) {
          // 当选择的结果是错误的时候
          ans_error.x = this.x + (windowWidth * 15) / DESIGN_HEIGHT
          ans_error.y = this.y + (windowHeight * 185) / DESIGN_WIDTH
          ans_error.visible = true
          ans_right.visible = false
          // 调用选择错误时候的音效
          playAudio('../../audio/L1/错误音效.mp3').then((resolve) => {
            resolve.addEventListener('ended', function () {
              playicon.css(toPlay)
              setTimeout(function () {
                clearAlpha(cupArray)
                ans_error.visible = false
              }, 1000)
            })
          })
        }
      }

      // 皇冠返回原位置的方法
      function crownBack(sprite) {
        sprite.x = initX
        sprite.y = initY
      }

      //  皇冠落入烧杯的动画效果的实现
      function intoCup(sprite1, sprite2) {
        sprite2.ishave = true
        sprite1.y = sprite2.y + (windowHeight * 65) / DESIGN_WIDTH
        sprite1.x = sprite2.x + sprite2.width
        let movedown = true
        let checkable = false,
          check_count = 0
        playAudio('../../audio/L1/皇冠入水音效.wav').then((resolve) => {
          resolve.addEventListener('ended', function () {
            playicon.css(toPlay)
          })
        })
        sprite1.interactive = false
        let interval = setInterval(function () {
          if (
            sprite1.x > sprite2.x + (windowWidth * 25) / DESIGN_WIDTH &&
            movedown
          ) {
            sprite1.x -= 1
          } else {
            sprite1.alpha = 0.5
            movedown = false
            checkable = true
            check_count++
            sprite2.ishave = true
            window.clearInterval(interval)
            changeCup(sprite1, sprite2)
            sprite1.buttonMode = false
            console.log(sprite1)
            if (checkable && check_count == 1) {
              checkAllUsed()
            }
          }
        }, 1000 / 60)
      }

      // 根据皇冠确定木桶一处的水量
      function changeCup(sprite1, sprite2) {
        if (sprite1.name == 'huangguan_1') {
          sprite2.texture =
            loader.resources['../../images/rowimages_01/漫水多.png'].texture
          sprite2.isLargest = true
        } else if (sprite1.name == 'huangguan_2') {
          sprite2.texture =
            loader.resources['../../images/rowimages_01/漫水中.png'].texture
          sprite2.isLargest = false
        } else {
          sprite2.texture =
            loader.resources['../../images/rowimages_01/漫水少.png'].texture
          sprite2.isLargest = false
        }
      }

      // 检查是不是所有的烧杯都用完了
      function checkAllUsed() {
        let use_out = true
        cupArray.forEach((element) => {
          if (!element.ishave) {
            use_out = false
          }
        })
        if (use_out & (message == null)) {
          // 更换文本提示信息
          message = new PIXI.Text(
            '小朋友，请找出体积最大的皇冠，并点击选择出来吧！',
            {
              fontFamily: 'Arial',
              fontSize: (windowHeight * 36) / DESIGN_WIDTH,
              align: 'center',
            }
          )
          message.rotation = Math.PI / 2
          message.y = (windowHeight - message.width) / 2
          message.x = (windowWidth * 555) / DESIGN_HEIGHT
          app.stage.addChild(message)
          // 确定所有的木桶都有了皇冠之后,才给木桶增加了交互属性,让小朋友可以选择.
          playAudio('../../audio/L1/请选择最大的皇冠.mp3').then((resolve) => {
            resolve.addEventListener('ended', function (e) {
              playicon.css(toPlay)
              cupArray.forEach((element) => {
                element.interactive = true
              })
            })
          })
        }
      }

      function gameLoop() {
        requestAnimationFrame(gameLoop)
        state()
        tink.update()
        app.renderer.render(app.stage)
      }

      async function playAudio(url) {
        if (audio) {
          audio.pause()
        }
        // let audio;
        audio = new Audio(url)
        playicon.css(playing)
        audio.play()
        currentAudioUrl = url
        return audio
      }

      // 选择结果之后的透明度处理
      function alphaAdd(sprite, spriteArray) {
        spriteArray.forEach(function (value, index, array) {
          console.log(value)
          value.alpha = 1
          if (sprite.id !== value.id) {
            value.alpha = 0.5
          }
        })
      }

      function clearAlpha(spriteArray) {
        spriteArray.forEach(function (value, index, array) {
          value.alpha = 1
        })
      }

      function play() {}

      //对页面的顶端返回条进行设置
      let backbar = $('#backbar')
      backbar.css({
        width: windowHeight,
        height: (windowWidth * 114) / DESIGN_HEIGHT,
        'line-height': (windowWidth * 114) / DESIGN_HEIGHT + 'px',
        transform: 'rotate(90deg)',
        'transform-origin': '0% 0%',
        top: 0,
        left: windowWidth,
      })

      let backbutton = $('#backbutton')
      backbutton.css('line-height', (windowWidth * 114) / DESIGN_HEIGHT + 'px')
      backbutton.css('width', backbutton.height())
      backbutton.css('text-align', 'center')
      backbutton.on('click', function (e) {
        e.stopPropagation()
        location.href = '../../index.html'
      })

      let backtitle = $('#backtitle')
      backtitle.css('line-height', (windowWidth * 80) / DESIGN_HEIGHT + 'px')

      let playicon = $('#playicon')
      playicon.css('width', (windowWidth * 80) / DESIGN_HEIGHT + 'px')
      playicon.on('click', function (e) {
        e.stopPropagation()
        playAudio(currentAudioUrl).then((resolve) => {
          resolve.addEventListener('ended', function () {
            playicon.css(toPlay)
          })
        })
      })

      // 对实验的遮罩层进行设置
      let shadowPanel = $('.shadowPanel')
      shadowPanel.hide()
      shadowPanel.css({
        width: windowHeight,
        height: windowWidth,
        'transform-origin': '0% 0%',
        left: windowWidth,
      })

      // 获取再看一遍的按钮
      let replay = $('.replay')
      replay.bind('click', function (e) {
        location.href = ''
        shadowPanel.hide()
        playAudio('../../audio/L1/三个皇冠拖入桶中.mp3').then((resolve) => {
          resolve.addEventListener('ended', function () {
            playicon.css(toPlay)
          })
        })
      })

      let nextItem = $('.nextItem')
      nextItem.bind('click', function (e) {
        window.location.replace('./course_report_01.html')
        shadowPanel.hide()
      })

      initApp()
      setBackground()
      createCupSpriteOne()
      createCupSpriteTwo()
      createCupSpriteThree()
      crateCrownScriptOne()
      crateCrownScriptTwo()
      crateCrownScriptThree()
      createResultSprite()
      playAudio('../../audio/L1/三个皇冠拖入桶中.mp3').then((resolve) => {
        resolve.addEventListener('ended', function () {
          playicon.css(toPlay)
        })
      })
      gameLoop()
    }
  </script>
</html>
